<template>
  <div class="pro-form-modal">
    <CardItem tabName="网络信息">
      <template #real>
        <div class="sever-info">
          <div>
            <span>网络类型</span
            ><span>
              {{ netTypeEnum[realTimeData.networkType as keyof typeof netTypeEnum] || '-' }}</span
            >
          </div>
          <div>
            <span>信号强度</span
            ><span
              >{{
                realTimeData.networkType == '1'
                  ? ''
                  : realTimeData.signalStrength
                    ? (
                        ((Number(realTimeData.signalStrength) + 1) / 5) *
                        100
                      ).toFixed(0) + '%'
                    : '-'
              }}
            </span>
          </div>
          <div>
            <span>网络信号</span
            ><span>{{
              realTimeData.networkSignal
                ? realTimeData.networkSignal + 'dbm'
                : '-'
            }}</span>
          </div>
          <div>
            <span>延时</span
            ><span>
              {{
                realTimeData.timeDelay ? realTimeData.timeDelay + 'ms' : '-'
              }}</span
            >
          </div>
          <div>
            <span>设备内网IP</span
            ><span>{{ realTimeData.deviceIp || '-' }}</span>
          </div>
          <div>
            <span>设备公网IP</span
            ><span>{{ realTimeData.devicePublicIp || '-' }}</span>
          </div>
          <div>
            <span>imei</span
            ><span
              :style="{
                color:
                  form.onlineStatus == '0' ? '#6ad7ca' : 'var(--text-color)',
              }"
              >{{
                form.onlineStatus == '0' ? form.imei : realTimeData.imei
              }}</span
            >
          </div>
          <div>
            <span>iccid</span
            ><span
              :style="{
                color:
                  form.onlineStatus == '0' ? '#6ad7ca' : 'var(--text-color)',
              }"
              >{{
                form.onlineStatus == '0' ? form.iccid : realTimeData.iccid
              }}</span
            >
          </div>
          <div>
            <span>imsi</span
            ><span
              :style="{
                color:
                  form.onlineStatus == '0' ? '#6ad7ca' : 'var(--text-color)',
              }"
              >{{
                form.onlineStatus == '0' ? form.imsi : realTimeData.imsi
              }}</span
            >
          </div>
          <div>
            <span>msisdn</span
            ><span
              :style="{
                color:
                  form.onlineStatus == '0' ? '#6ad7ca' : 'var(--text-color)',
              }"
              >{{
                form.onlineStatus == '0' ? form.msisdn : realTimeData.msisdn
              }}</span
            >
          </div>
        </div>
      </template>
      <template #history>
        <RangePickerCom
          v-model:timeValue="netWorkTime"
          :searchApi="handleNetSearch"
        >
          <div class="device-userate" ref="networkRef"></div>
        </RangePickerCom>
      </template>
      <template #other v-if="form.simType == '1' || form.simType == '2'">
        <TabTitle tabName="SIM信息" />
        <div class="card-container flex">
          <div v-if="form.simType == '1'" class="flex">
            <div code="device:sim:detail" class="mr-2">
              <Space>
                <Button @click="handlePoolInfo">流量池信息</Button>
                <Button @click="handleCardInfo">卡流量信息</Button>
                <Button @click="handleCardDetail">卡详情</Button>
              </Space>
            </div>
            <div code="device:sim:operation" class="mr-2">
              <Space>
                <Button @click="handleStopCard">停机</Button>
                <Button @click="handleResumeCard">复机</Button>
                <Button @click="handleRebindCard">换绑</Button>
              </Space>
            </div>
          </div>
          <div v-if="form.simType == '2'" class="flex">
            <div code="device:sim:detail" class="mr-2">
              <Space>
                <Button @click="handleLxCardInfo">卡流量信息</Button>
                <Button @click="handleLxCardDetail">卡详情</Button>
                <Button @click="handleLxPoolInfo">流量池统计</Button>
              </Space>
            </div>
            <div code="device:sim:operation" class="mr-2">
              <Space>
                <Button @click="handleLxStopCard">停机</Button>
                <Button @click="handleLxResumeCard">复机</Button>
              </Space>
            </div>
          </div>
        </div>
      </template>
    </CardItem>
    <!-- AL流量池信息 -->
    <Modal
      v-model:open="visibleAlyPool"
      width="40%"
      :mask-closable="false"
      :keyboard="false"
      :footer="null"
      centered
      destroy-on-close
    >
      <AlyPoolModal
        v-model:alyPoolStatistics="alyPoolStatistics"
        v-model:dateAlyPool="dateAlyPool"
      />
    </Modal>
    <!-- 卡流量信息 -->
    <Modal
      v-model:open="visibleAlyFlow"
      width="50%"
      :mask-closable="false"
      :keyboard="false"
      :footer="null"
      centered
      destroy-on-close
    >
      <div class="card-container">
        <DatePicker
          :clearable="false"
          v-model:value="dateAlyFlow"
          value-format="YYYYMM"
          picker="month"
          @change="changeAlyFlowDate"
        />
        <div id="aly-flow" style="width: 100%; height: 400px"></div>
      </div>
    </Modal>
    <!-- 卡详情 -->
    <Modal
      title="物联网卡详情"
      v-model:open="visibleAlyCard"
      width="40%"
      :mask-closable="false"
      :keyboard="false"
      :footer="null"
      centered
      destroy-on-close
    >
      <AlyCardModal :cardDetail="cardDetail" />
    </Modal>

    <!-- dateLxFlow -->
    <Modal
      v-model:open="visibleLxFlow"
      :width="1400"
      :mask-closable="false"
      :keyboard="false"
      :footer="null"
      centered
      destroy-on-close
    >
      <div class="card-container">
        <DatePicker
          :clearable="false"
          v-model:value="dateLxFlow"
          value-format="YYYYMM"
          picker="month"
          @change="changeLxFlowDate"
        />
        <div id="lx-flow" style="width: 100%; height: 400px"></div>
      </div>
    </Modal>
    <!-- handleLxCardInfo -->
    <Modal
      title="物联网卡详情"
      v-model:open="visibleLxCard"
      width="40%"
      :mask-closable="false"
      :keyboard="false"
      :footer="null"
      centered
      destroy-on-close
    >
      <LxCardModal :lxCardDetail="lxCardDetail"></LxCardModal>
    </Modal>
    <!-- AL流量池信息 -->
    <Modal
      v-model:open="visibleLxPool"
      width="40%"
      :mask-closable="false"
      :keyboard="false"
      :footer="null"
      centered
      destroy-on-close
    >
      <LxPoolModal
        v-model:lxPoolStatistics="lxPoolStatistics"
        v-model:dateLxPool="dateLxPool"
      />
    </Modal>
  </div>
</template>
<script setup lang="tsx">
import { onUnmounted, ref } from 'vue';
import { Button, DatePicker, Modal, RangePicker, Space } from 'ant-design-vue';
import * as echarts from 'echarts';
import 'echarts-liquidfill/src/liquidFill.js';
import 'echarts/theme/macarons';
import moment from 'moment';
import {
  getAlyCardDetail,
  getAlyFlowInfo,
  getAlyPoolStatistics,
  getAlyRebindCard,
  getAlyResumeCard,
  getAlyStopCard,
  getDevice,
  getDeviceRealTimeData,
  getLxCardDetail,
  getLxFlowInfo,
  getLxPoolStatistics,
  getLxResumeSingleCard,
  getLxStopSingleCard,
  getNetworkWaveform,
  getSIMCardType,
  getTimeDelayWaveform,
} from '@/api/device';
import { netTypeEnum } from '../../contants';
import CardItem from '../comm/CardItem.vue';
import TabTitle from '../comm/TabTitle.vue';
import AlyCardModal from '../modal/AlyCardModal.vue';
import AlyPoolModal from '../modal/AlyPoolModal.vue';
import LxCardModal from '../modal/LxCardModal.vue';
import LxPoolModal from '../modal/LxPoolModal.vue';
import RangePickerCom from './RangePickerCom.vue';

interface Props {
  pageData: any;
  realTimeData: {
    networkType?: string | number;
    signalStrength?: string | number;
    networkSignal?: string;
    timeDelay?: string;
    deviceIp?: string;
    devicePublicIp?: string;
    imei?: string;
    iccid?: string;
    imsi?: string;
    msisdn?: string;
  };
}
const props = defineProps<Props>();

// 历史数据-查询时间
const netWorkTime = ref<any>(null);
// 网络历史数据查询
const handleNetSearch = async () => {
  const res = await getNetworkWaveform({
    code: props.pageData.code,
    startTime: netWorkTime.value?.[0],
    endTime: netWorkTime.value?.[1],
  });
  const res1 = await getTimeDelayWaveform({
    code: props.pageData.code,
    startTime: netWorkTime.value?.[0],
    endTime: netWorkTime.value?.[1],
  });

  networkChartInit(res.data, res1.data);
};

// 网络折线图初始化
const networkRef = ref<any>(null);
const chartNetWork = ref<any>(null);
const networkChartInit = (data: any, delaydata: any) => {
  networkRef.value.style.height = '500px';
  const networkChart = echarts.init(networkRef.value);
  let option = {
    title: [
      {
        top: '3%',
        text: '网络信号',
        textStyle: {
          color: '#fff',
        },
      },
      {
        top: '52%',
        text: '网络延时',
        textStyle: {
          color: '#fff',
        },
      },
    ],

    tooltip: {
      trigger: 'axis',
    },
    grid: [
      {
        top: '10%',
        bottom: '52%',
      },
      {
        top: '60%',
        bottom: '5%',
      },
    ],
    xAxis: [
      {
        type: 'category',
        data: data.xdata,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          textStyle: {
            color: '#fff',
          },
          formatter: function (value: any) {
            return value.split('.')[0];
          },
          showMaxLabel: true,
        },
      },
      {
        gridIndex: 1,
        type: 'category',
        data: delaydata.xdata,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          textStyle: {
            color: '#fff',
          },
          formatter: function (value: any) {
            return value.split('.')[0];
          },
          showMaxLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        inverse: true,
        axisLabel: {
          textStyle: {
            color: '#fff',
          },
          formatter: function (value: any) {
            return value != 0 ? value + 'db' : value;
          },
          showMaxLabel: true,
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: 'rgba(255, 255, 255, .14)',
            type: 'dashed',
          },
        }, // 网格线
        axisLine: {
          onZero: false,
        },
      },
      {
        gridIndex: 1,
        type: 'value',
        axisLabel: {
          textStyle: {
            color: '#fff',
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: 'rgba(255, 255, 255, .14)',
            type: 'dashed',
          },
        }, // 网格线
      },
    ],
    series: [
      {
        name: '网络信号',
        data: data.networkSignalData,
        type: 'line',
        showSymbol: false,
        // tooltip: {  // 第一个图表的 tooltip 格式化
        //   show:true,
        //   trigger: 'item',
        //   formatter: '{b}<br />{a}:-{c}db'
        // }
      },
      {
        name: '网络延时',
        data: delaydata.timeDelay,
        type: 'line',
        showSymbol: false,
        xAxisIndex: 1,
        yAxisIndex: 1,
        // tooltip: {  // 第一个图表的 tooltip 格式化
        //   show:true,
        //   trigger: 'item',
        //   formatter: '{b}<br />{a}:{c}ms'
        // }
      },
    ],
  };
  networkChart.setOption(option);
};
// const changeInitCalendarPage = () => {
//   // let element = document.querySelectorAll(
//   //   '.el-picker-panel__icon-btn.el-icon-arrow-left',
//   // );
//   // console.log(element, 'element');
//   // if (element) element[element.length - 1].click();
//   console.log('click--');
// };

const form = ref<any>({});

const _getSIMCardType = async () => {
  let res: any = await getSIMCardType({
    iccid: form.value.iccid,
  });
  if (res.code == 200) {
    if (res.msg.length == 1) {
      form.value.simType = res.msg;
    }
  }
};

// 实时数据查询
const realTimeData = ref<any>({});
const realTime = async () => {
  const res = await getDeviceRealTimeData(props.pageData.deviceId);
  if (res.code == 200) {
    realTimeData.value = res.data || {};
    if (Object.keys(realTimeData.value).length == 0) {
      return;
    }
  }
};

// 获取实时信息
const timer: any = ref(null);
const getRealTimeData = () => {
  timer.value = setInterval(() => {
    realTime();
  }, 5000);
};

getDevice(props.pageData.deviceId).then(async (response: any) => {
  form.value = response.data;

  if (form.value.iccid) {
    _getSIMCardType();
  }
  if (form.value.onlineStatus == '1') {
    realTime();
    getRealTimeData();
  }
});

onUnmounted(() => {
  clearInterval(timer.value);
});

// 查询流量池信息
const alyPoolStatistics = ref({ credentialType: '' });
const getAlyPoolInfo = async (date: any) => {
  console.log(date, 'date');

  getAlyPoolStatistics({ date }).then((res: any) => {
    console.log(res, 'res');

    alyPoolStatistics.value = res.data;
  });
};

const visibleAlyPool = ref(false);
const dateAlyPool = ref('');
const handlePoolInfo = () => {
  visibleAlyPool.value = true;
  dateAlyPool.value = moment(new Date()).format('YYYYMM');
  getAlyPoolInfo(dateAlyPool.value);
};
// 卡流量信息
const visibleAlyFlow = ref(false);
const dateAlyFlow = ref('');

const changeAlyFlowDate = async (val: any) => {
  _getAlyFlowInfo(val);
};

const handleCardInfo = () => {
  visibleAlyFlow.value = true;
  dateAlyFlow.value = moment(new Date()).format('YYYYMM');
  _getAlyFlowInfo(dateAlyFlow.value);
};

const lineChart = ref<any>(null);
const alyFlowInfo = ref<any>({});
const _getAlyFlowInfo = (date: any) => {
  getAlyFlowInfo({
    iccid: form.value.iccid,
    date,
  }).then((res: any) => {
    alyFlowInfo.value = res.data.listCardMonthFlow[0];
    let xAxis = alyFlowInfo.value.listDayFlow.map((item: any) => {
      return item.day;
    });
    let yData = alyFlowInfo.value.listDayFlow.map((item: any) => {
      return item.flow.replace('MB', '');
    });
    lineChart.value = echarts.init(document.getElementById('aly-flow'));
    let option = {
      title: {
        top: '5%',
        text: '流量(MB)',
        textStyle: {
          fontSize: 16,
          color: '#fff',
        },
      },
      tooltip: {
        trigger: 'axis',
      },
      xAxis: {
        type: 'category',
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: '#fff',
        },
        data: xAxis,
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#fff',
        },
        splitLine: {
          show: false,
        },
      },
      series: [
        {
          type: 'line',
          smooth: true,
          data: yData,
        },
      ],
    };
    lineChart.value.setOption(option);
  });
};
const handleCardDetail = () => {
  _getAlyCardDetail();
};
const cardDetail = ref<any>({});
const visibleAlyCard = ref(false);
const _getAlyCardDetail = () => {
  getAlyCardDetail({
    iccid: form.value.iccid,
  }).then((res: any) => {
    cardDetail.value = res.data.vsimCardInfo;
    visibleAlyCard.value = true;
    console.log(res, 'iccid');
  });
};
const handleStopCard = () => {
  Modal.confirm({
    title: '确认操作',
    content: '是否确认停机?',
    async onOk() {
      await getAlyStopCard({ iccid: form.value.iccid });
      Modal.success({
        title: '操作成功',
      });
    },
    onCancel() {
      console.log('用户点击了取消');
    },
  });
};

const handleResumeCard = () => {
  Modal.confirm({
    title: '确认操作',
    content: '是否确认复机？',
    async onOk() {
      await getAlyResumeCard({ iccid: form.value.iccid });
      Modal.success({
        title: '操作成功',
      });
    },
    onCancel() {
      console.log('用户点击了取消');
    },
  });
};
const handleRebindCard = () => {
  Modal.confirm({
    title: '确认操作',
    content: '是否确认换绑？',
    async onOk() {
      await getAlyRebindCard({ iccid: form.value.iccid });
      Modal.success({
        title: '操作成功',
      });
    },
    onCancel() {
      console.log('用户点击了取消');
    },
  });
};

const visibleLxFlow = ref(false);
const dateLxFlow = ref('');
const handleLxCardInfo = () => {
  visibleLxFlow.value = true;
  dateLxFlow.value = moment(new Date()).format('YYYYMM');
  _getLxFlowInfo(dateLxFlow.value);
};
const _getLxFlowInfo = (date: any) => {
  getLxFlowInfo({
    iccid: form.value.iccid,
    date,
  })
    .then((res: any) => {
      let xAxis = res.data.data.rows.map((item: any) => {
        return item.date;
      });
      let yData = res.data.data.rows.map((item: any) => {
        return item.data_usage;
      });
      let chart = echarts.init(document.getElementById('lx-flow'));
      let option = {
        title: {
          top: '5%',
          text: '流量(MB)',
          textStyle: {
            fontSize: 16,
            color: '#fff',
          },
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: '#fff',
          },
          data: xAxis,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#fff',
          },
          splitLine: {
            show: false,
          },
        },
        series: [
          {
            type: 'line',
            smooth: true,
            data: yData,
          },
        ],
      };
      chart.setOption(option);
    })
    .catch((err) => {});
};

const changeLxFlowDate = (val: any) => {
  getLxFlowInfo(val);
};
const lxCardDetail = ref<any>({});
const visibleLxCard = ref(false);
const handleLxCardDetail = () => {
  getLxCardDetail({
    iccid: form.value.iccid,
  }).then((res: any) => {
    lxCardDetail.value = res.data.data;
    visibleLxCard.value = true;
    console.log(res, 'iccid');
  });
};

// 流量池计费组统计
const lxPoolStatistics = ref({});
const getLxPoolInfo = async (date: any) => {
  getLxPoolStatistics({ date }).then((res: any) => {
    console.log(res, 'res');
    lxPoolStatistics.value = res.data.data.rows;
    visibleLxPool.value = true;
  });
};

const visibleLxPool = ref(false);
const dateLxPool = ref('');
const handleLxPoolInfo = () => {
  dateLxPool.value = moment(new Date()).format('YYYYMM');
  getLxPoolInfo(dateLxPool.value);
};
const handleLxStopCard = () => {
  Modal.confirm({
    title: '确认操作',
    content: '是否确认停机？',
    async onOk() {
      await getLxStopSingleCard({ iccid: form.value.iccid });
      Modal.success({
        title: '操作成功',
      });
    },
    onCancel() {
      console.log('用户点击了取消');
    },
  });
};
const handleLxResumeCard = () => {
  Modal.confirm({
    title: '确认操作',
    content: '是否确认复机？',
    async onOk() {
      await getLxResumeSingleCard({ iccid: form.value.iccid });
      Modal.success({
        title: '操作成功',
      });
    },
    onCancel() {
      console.log('用户点击了取消');
    },
  });
};
</script>
<style lang="scss" scoped>
.sever-info {
  > div {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid var(--custom-row-data);
    color: var(--custom-sever-info);

    > span:last-child {
      display: flex;
      align-content: center;
      color: var(--text-color);

      .svg-icon {
        margin-left: 10px;
        width: 14px;
        height: 14px;
      }
    }
  }
}

.device-search {
  position: relative;
  margin: 20px 0;

  .search-time {
    margin: 0 20px;
    color: var(--text-color);
    font-weight: 600;
  }
}
</style>
